package com.ruoyi.project.cardbox.outbound.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.project.cardbox.inbound.domain.OrderInbound;
import com.ruoyi.project.cardbox.inbound.service.IOrderInboundService;
import com.ruoyi.project.cardbox.orders.domain.OrderStatus;
import com.ruoyi.project.cardbox.orders.domain.Orders;
import com.ruoyi.project.cardbox.orders.service.IOrdersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.project.cardbox.outbound.mapper.OrderOutboundMapper;
import com.ruoyi.project.cardbox.outbound.domain.OrderOutbound;
import com.ruoyi.project.cardbox.outbound.service.IOrderOutboundService;
import com.ruoyi.common.utils.text.Convert;
import org.springframework.transaction.annotation.Transactional;

/**
 * 出库单Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-07-04
 */
@Service
public class OrderOutboundServiceImpl extends ServiceImpl<OrderOutboundMapper, OrderOutbound> implements IOrderOutboundService
{
    @Autowired
    private OrderOutboundMapper orderOutboundMapper;
    @Autowired
    private IOrderInboundService orderInboundService;
    @Autowired
    private IOrdersService ordersService;

    /**
     * 查询出库单
     * 
     * @param id 出库单主键
     * @return 出库单
     */
    @Override
    public OrderOutbound selectOrderOutboundById(Long id)
    {
        return orderOutboundMapper.selectOrderOutboundById(id);
    }

    /**
     * 查询出库单列表
     * 
     * @param orderOutbound 出库单
     * @return 出库单
     */
    @Override
    public List<OrderOutbound> selectOrderOutboundList(OrderOutbound orderOutbound)
    {
        return orderOutboundMapper.selectOrderOutboundList(orderOutbound);
    }

    /**
     * 新增出库单
     * 
     * @param orderOutbound 出库单
     * @return 结果
     */
    @Override
    public int insertOrderOutbound(OrderOutbound orderOutbound)
    {
        orderOutbound.setCreateTime(DateUtils.getNowDate());
        return orderOutboundMapper.insertOrderOutbound(orderOutbound);
    }

    /**
     * 修改出库单
     * 
     * @param orderOutbound 出库单
     * @return 结果
     */
    @Override
    public int updateOrderOutbound(OrderOutbound orderOutbound)
    {
        orderOutbound.setUpdateTime(DateUtils.getNowDate());
        //判断纸箱售价是否为空
        if(orderOutbound.getUnitPrice() == null){
            throw new ServiceException("请填写纸箱售价");
        }
        if(orderOutbound.getQuantity() == null){
            throw new ServiceException("请填写出库数量");
        }
        if(orderOutbound.getQuantity() <= 0){
            throw new ServiceException("出库数量必须大于0");
        }
        if(orderOutbound.getCarriage() == null){
            orderOutbound.setCarriage(BigDecimal.ZERO);
        }
        if(orderOutbound.getRebate()== null){
            orderOutbound.setRebate(BigDecimal.ZERO);
        }
        //计算单个利润
        BigDecimal profit = orderOutbound.getUnitPrice().subtract(orderOutbound.getRebate());
        orderOutbound.setProfit(profit);
        // 金额 = (售价 - 回扣) * 数量
        orderOutbound.setAmount(profit.multiply(BigDecimal.valueOf(orderOutbound.getQuantity())));

        return orderOutboundMapper.updateOrderOutbound(orderOutbound);
    }

    /**
     * 批量删除出库单
     * 
     * @param ids 需要删除的出库单主键
     * @return 结果
     */
    @Override
    public int deleteOrderOutboundByIds(String ids)
    {
        String[] idArray = Convert.toStrArray(ids);
        int deleteCount = 0;

        for (String idStr : idArray) {
            Long id = null;
            try {
                id = Long.parseLong(idStr);
            } catch (NumberFormatException e) {
                // id格式不正确，跳过
                continue;
            }

            // 查询出库单，不存在跳过

            OrderOutbound orderOutbound=this.getById(id);
            if (orderOutbound == null) {
                continue;
            }

            // 查询主订单，不存在跳过
            LambdaQueryWrapper<Orders> orderWrapper = new LambdaQueryWrapper<>();
            orderWrapper.eq(Orders::getOrderId, orderOutbound.getOrderId());
            Orders order = ordersService.getOne(orderWrapper);
            if (order == null) {
                continue;
            }

            // 订单状态不是“请购”，跳过
            if (order.getStatus() != OrderStatus.OUT_STOCK) {
                continue;
            }

            // 符合条件，删除请购单
            boolean removed = this.removeById(id);
            if (removed) {
                deleteCount++;
                // 更新主订单状态为入库
                order.setStatus(OrderStatus.IN_STOCK);
                ordersService.updateById(order);
            }
        }

        return deleteCount;
    }

    /**
     * 删除出库单信息
     * 
     * @param id 出库单主键
     * @return 结果
     */
    @Override
    public int deleteOrderOutboundById(Long id)
    {
        return orderOutboundMapper.deleteOrderOutboundById(id);
    }

    @Override
    public void createOutboundReceipt(Orders order) {
        if (order.getOrderId() == null) {
            throw new ServiceException("订单编号不能为空");
        }
        // 1. 根据 orderId 查询 入库 记录
        LambdaQueryWrapper<OrderInbound> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(OrderInbound::getOrderId, order.getOrderId());
        OrderInbound orderInbound = orderInboundService.getOne(queryWrapper);
        if (orderInbound == null) {
            throw new RuntimeException("未找到对应的入库单");
        }

        OrderOutbound outbound = new OrderOutbound();
        outbound.setOrderId(order.getOrderId());
        outbound.setCustomerName(order.getCustomerName());
        outbound.setProductName(order.getProductName());
        outbound.setFluteType(orderInbound.getFluteType());
        outbound.setLayerCount(orderInbound.getLayerCount());
        outbound.setCreateTime(DateUtils.getNowDate());
        outbound.setUpdateTime(DateUtils.getNowDate());
        this.save(outbound);
    }

    @Override
    public List<OrderOutbound> selectOrderOutboundByIds(List<String> ids) {
        return orderOutboundMapper.selectOrderOutboundByIds(ids);
    }
}
